import React, { useState, useEffect, useCallback } from 'react';
import { Divider, Button, Card, Row, Col, Statistic, Progress, Spin, Alert, Tag } from 'antd';
import { 
    FileTextOutlined, 
    CodeOutlined, 
    CommentOutlined, 
    ClockCircleOutlined,
    CheckCircleOutlined,
    ExclamationCircleOutlined,
    SyncOutlined
} from '@ant-design/icons';
import { 
    getStatisticsOverview, 
    getLanguageComposition, 
    UnitStatisticsDTO, 
    LanguageCompositionDTO 
} from '../../services/statistics';
import { getUnit } from '../../services/unit';

// 基于接口定义的数据类型
export interface UnitInfoData {
    unitId?: string;
    appId?: string;
    gitRepoUrl?: string;
    defaultBranch?: string;
    ownTeam?: string;
    ownCenter?: string;
    owner?: string;
    staticScan?: boolean;
    gitScan?: boolean;
    apmScan?: boolean;
    saScan?: boolean;
    packageFilter?: string;
    classFilter?: string;
    methodFilter?: string;
    creator?: string;
    createTime?: string;
}

interface UnitInfoProps {
    unitId: string; // 改为直接接收unitId
    onEdit?: () => void;
}

const UnitInfo: React.FC<UnitInfoProps> = ({ unitId, onEdit }) => {
    const [unitInfo, setUnitInfo] = useState<UnitInfoData | null>(null);
    const [statistics, setStatistics] = useState<UnitStatisticsDTO | null>(null);
    const [languageComposition, setLanguageComposition] = useState<LanguageCompositionDTO[]>([]);
    const [loading, setLoading] = useState(false);
    const [unitInfoLoading, setUnitInfoLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [unitInfoError, setUnitInfoError] = useState<string | null>(null);

    // 加载单元基本信息
    const loadUnitInfo = useCallback(async () => {
        if (!unitId) return;
        
        setUnitInfoLoading(true);
        setUnitInfoError(null);
        
        try {
            console.log('Loading unit info for:', unitId);
            const res = await getUnit(unitId);
            console.log('Unit info response:', res);
            
            // 兼容不同返回结构 { data: {...} } 或直接 {...}
            const dataRes = (res && res.data) ? res.data : res;
            setUnitInfo(dataRes || null);
        } catch (err: any) {
            console.error('Failed to load unit info:', err);
            const errorMessage = err?.response?.data?.msg || err?.message || '加载单元信息失败';
            setUnitInfoError(errorMessage);
            setUnitInfo(null);
        } finally {
            setUnitInfoLoading(false);
        }
    }, [unitId]);

    // 加载统计数据
    const loadStatistics = useCallback(async () => {
        if (!unitId) return;
        
        setLoading(true);
        setError(null);
        
        try {
            // 并行调用两个API获取数据
            const [overviewResponse, languagesResponse] = await Promise.all([
                getStatisticsOverview(unitId),
                getLanguageComposition(unitId)
            ]);
            
            console.log('UnitInfo - Overview response:', overviewResponse);
            console.log('UnitInfo - Languages response:', languagesResponse);
            
            // 处理概览数据响应格式
            let overviewData = null;
            if (overviewResponse && typeof overviewResponse === 'object') {
                if ('code' in overviewResponse && overviewResponse.code === 0 && overviewResponse.data) {
                    overviewData = overviewResponse.data;
                } else if ('totalFiles' in overviewResponse || 'totalLines' in overviewResponse) {
                    overviewData = overviewResponse;
                }
            }
            
            // 处理语言数据响应格式
            let languagesData: any[] = [];
            if (languagesResponse && typeof languagesResponse === 'object') {
                if ('code' in languagesResponse && languagesResponse.code === 0 && Array.isArray(languagesResponse.data)) {
                    languagesData = languagesResponse.data;
                } else if (Array.isArray(languagesResponse)) {
                    languagesData = languagesResponse;
                }
            }
            
            setStatistics(overviewData as UnitStatisticsDTO | null);
            setLanguageComposition(languagesData as LanguageCompositionDTO[]);
            
            console.log('UnitInfo - Processed overview data:', overviewData);
            console.log('UnitInfo - Processed languages data:', languagesData);
            
        } catch (err: any) {
            setError(err?.response?.data?.msg || '加载统计信息失败');
            console.error('加载统计信息失败:', err);
        } finally {
            setLoading(false);
        }
    }, [unitId]);

    // 加载所有数据
    const loadAllData = useCallback(async () => {
        await Promise.all([
            loadUnitInfo(),
            loadStatistics()
        ]);
    }, [loadUnitInfo, loadStatistics]);

    useEffect(() => {
        loadAllData();
    }, [loadAllData]);

    // 获取扫描状态显示
    const getScanStatusDisplay = (status: string) => {
        switch(status) {
            case 'SCANNING':
                return { 
                    icon: <SyncOutlined spin />, 
                    text: '扫描中', 
                    color: 'processing',
                    tagColor: 'processing'
                };
            case 'SUCCESS':
                return { 
                    icon: <CheckCircleOutlined />, 
                    text: '扫描完成', 
                    color: 'success',
                    tagColor: 'success'
                };
            case 'FAILED':
                return { 
                    icon: <ExclamationCircleOutlined />, 
                    text: '扫描失败', 
                    color: 'error',
                    tagColor: 'error'
                };
            default:
                return { 
                    icon: <ExclamationCircleOutlined />, 
                    text: '未知状态', 
                    color: 'default',
                    tagColor: 'default'
                };
        }
    };

    // 格式化时间
    const formatTime = (timeStr: string) => {
        try {
            return new Date(timeStr).toLocaleString('zh-CN');
        } catch {
            return timeStr;
        }
    };

    // 计算代码质量指标
    const getCodeQualityMetrics = () => {
        if (!statistics) return null;
        
        const codeDensity = (statistics.totalCodeLines / statistics.totalLines * 100).toFixed(1);
        const commentRate = (statistics.totalCommentLines / statistics.totalLines * 100).toFixed(1);
        const blankLineRate = (statistics.totalBlankLines / statistics.totalLines * 100).toFixed(1);
        
        return { codeDensity, commentRate, blankLineRate };
    };

    const qualityMetrics = getCodeQualityMetrics();

    // 如果统计信息还在加载中
    if (loading) {
        return (
            <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" />
                <div style={{ marginTop: '16px' }}>加载统计信息中...</div>
            </div>
        );
    }

    // 如果统计信息加载失败
    if (error) {
        return (
            <div style={{ maxWidth: 800, margin: '0 auto', padding: '24px' }}>
                <Alert 
                    message="加载失败" 
                    description={error}
                    type="error" 
                    showIcon 
                    action={
                        <Button size="small" onClick={loadAllData}>
                            重试
                        </Button>
                    }
                />
            </div>
        );
    }

    // 如果没有统计信息
    if (!statistics) {
        return (
            <div style={{ maxWidth: 800, margin: '0 auto', padding: '24px' }}>
                <Alert 
                    message="无数据" 
                    description="未找到单元统计信息，请先执行统计分析"
                    type="warning" 
                    showIcon 
                />
            </div>
        );
    }

    return (
        <div style={{ maxWidth: 1200, margin: '0 auto' }}>
            {/* 仓库统计信息块 - 新增 */}
            <Card 
                title={
                    <span>
                        <CodeOutlined style={{ marginRight: 8 }} />
                        仓库统计信息
                    </span>
                }
                style={{ marginBottom: 24 }}
                extra={
                    <Button 
                        size="small" 
                        onClick={loadStatistics} 
                        loading={loading}
                        icon={<SyncOutlined />}
                    >
                        刷新
                    </Button>
                }
            >
                {loading ? (
                    <div style={{ textAlign: 'center', padding: '40px' }}>
                        <Spin size="large" />
                        <div style={{ marginTop: '16px' }}>加载统计信息中...</div>
                    </div>
                ) : error ? (
                    <Alert message={error} type="error" showIcon />
                ) : statistics ? (
                    <>
                        {/* 核心统计指标 */}
                        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                            <Col span={6}>
                                <Statistic
                                    title="总文件数"
                                    value={statistics.totalFiles}
                                    prefix={<FileTextOutlined />}
                                    valueStyle={{ color: '#1890ff' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic
                                    title="总代码行数"
                                    value={statistics.totalLines}
                                    prefix={<CodeOutlined />}
                                    valueStyle={{ color: '#52c41a' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic
                                    title="有效代码行数"
                                    value={statistics.totalCodeLines}
                                    prefix={<CodeOutlined />}
                                    valueStyle={{ color: '#722ed1' }}
                                />
                            </Col>
                            <Col span={6}>
                                <Statistic
                                    title="注释行数"
                                    value={statistics.totalCommentLines}
                                    prefix={<CommentOutlined />}
                                    valueStyle={{ color: '#faad14' }}
                                />
                            </Col>
                        </Row>

                        {/* 代码质量指标 */}
                        {qualityMetrics && (
                            <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                                <Col span={8}>
                                    <div style={{ textAlign: 'center' }}>
                                        <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
                                            {qualityMetrics.codeDensity}%
                                        </div>
                                        <div style={{ color: '#666' }}>代码密度</div>
                                        <Progress 
                                            percent={parseFloat(qualityMetrics.codeDensity)} 
                                            size="small" 
                                            strokeColor="#52c41a"
                                            showInfo={false}
                                        />
                                    </div>
                                </Col>
                                <Col span={8}>
                                    <div style={{ textAlign: 'center' }}>
                                        <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#faad14' }}>
                                            {qualityMetrics.commentRate}%
                                        </div>
                                        <div style={{ color: '#666' }}>注释率</div>
                                        <Progress 
                                            percent={parseFloat(qualityMetrics.commentRate)} 
                                            size="small" 
                                            strokeColor="#faad14"
                                            showInfo={false}
                                        />
                                    </div>
                                </Col>
                                <Col span={8}>
                                    <div style={{ textAlign: 'center' }}>
                                        <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#1890ff' }}>
                                            {qualityMetrics.blankLineRate}%
                                        </div>
                                        <div style={{ color: '#666' }}>空行率</div>
                                        <Progress 
                                            percent={parseFloat(qualityMetrics.blankLineRate)} 
                                            size="small" 
                                            strokeColor="#1890ff"
                                            showInfo={false}
                                        />
                                    </div>
                                </Col>
                            </Row>
                        )}

                        {/* 扫描状态和工具信息 */}
                        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                            <Col span={8}>
                                <div style={{ textAlign: 'center' }}>
                                    <div style={{ marginBottom: 8 }}>
                                        {getScanStatusDisplay(statistics.scanStatus).icon}
                                    </div>
                                    <Tag color={getScanStatusDisplay(statistics.scanStatus).tagColor}>
                                        {getScanStatusDisplay(statistics.scanStatus).text}
                                    </Tag>
                                    <div style={{ fontSize: '12px', color: '#666', marginTop: 4 }}>
                                        扫描状态
                                    </div>
                                </div>
                            </Col>
                            <Col span={8}>
                                <div style={{ textAlign: 'center' }}>
                                    <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#722ed1' }}>
                                        {statistics.elapsedSeconds}s
                                    </div>
                                    <div style={{ color: '#666' }}>分析耗时</div>
                                </div>
                            </Col>
                            <Col span={8}>
                                <div style={{ textAlign: 'center' }}>
                                    <div style={{ fontSize: '12px', color: '#666' }}>
                                        {statistics.clocVersion}
                                    </div>
                                    <div style={{ color: '#666' }}>分析工具版本</div>
                                </div>
                            </Col>
                        </Row>

                        {/* 语言组成信息 */}
                        {languageComposition.length > 0 && (
                            <div>
                                <Divider orientation="left">编程语言组成</Divider>
                                <Row gutter={[16, 16]}>
                                    {languageComposition.map((lang, index) => (
                                        <Col span={6} key={index}>
                                            <Card size="small" style={{ textAlign: 'center' }}>
                                                <div style={{ 
                                                    width: '16px', 
                                                    height: '16px', 
                                                    backgroundColor: lang.color,
                                                    borderRadius: '50%',
                                                    margin: '0 auto 8px'
                                                }} />
                                                <div style={{ fontWeight: 'bold', marginBottom: 4 }}>
                                                    {lang.language}
                                                </div>
                                                <div style={{ fontSize: '12px', color: '#666', marginBottom: 4 }}>
                                                    {lang.fileCount} 文件
                                                </div>
                                                <div style={{ fontSize: '16px', fontWeight: 'bold', color: '#1890ff' }}>
                                                    {lang.percentage.toFixed(1)}%
                                                </div>
                                                <Progress 
                                                    percent={lang.percentage} 
                                                    size="small" 
                                                    strokeColor={lang.color}
                                                    showInfo={false}
                                                />
                                            </Card>
                                        </Col>
                                    ))}
                                </Row>
                            </div>
                        )}

                        {/* 最后扫描时间 */}
                        <div style={{ textAlign: 'center', marginTop: 16, color: '#666' }}>
                            <ClockCircleOutlined style={{ marginRight: 4 }} />
                            最后扫描时间: {formatTime(statistics.lastScanTime)}
                        </div>
                    </>
                ) : null}
            </Card>

        <div style={{ textAlign: 'right', marginTop: 16 }}>
            <Button type="primary" onClick={onEdit}>编辑</Button>
        </div>
    </div>
);
};

export default UnitInfo; 